<?php

namespace App\Repositories;


use Illuminate\Database\Eloquent\Model;

class BaseRepository
{

    protected $model;

    protected $condition = [];

    public function __construct(Model $model)
    {
        $this->model = $model;

    }

    public function where($condition = [])
    {
        $this->condition = $condition;
        return $this;
    }

    public function getList($columns = ['*'], $where = [], $page = 1, $limit = 15, $sort = 'created_at', $order = 'desc'): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $this->condition = array_merge($this->condition, $where);
        return $this->model->where($this->condition)
            ->orderBy($sort, $order)
            ->paginate($limit, $columns, 'page', $page);
    }

    public function getAll($where = [], $limit = 1000)
    {
        $this->condition = array_merge($this->condition, $where);
        return $this->model->where($this->condition)->limit($limit)->get();
    }

    public function getById($id)
    {
        return $this->model->where($this->condition)->find($id);
    }

    public function isExists($where)
    {
        $this->condition = array_merge($this->condition, $where);
        return $this->model->where($this->condition)->exists();
    }

    public function create(array $data)
    {
        return $this->model->create($data);
    }

    public function update($id, array $data)
    {
        $record = $this->getById($id);
        if ($record) {
            $record->update($data);
            return $record;
        }
        return null;
    }

    public function delete($id)
    {
        $record = $this->getById($id);
        if ($record) {
            $record->delete();
            return true;
        }
        return false;
    }


}